<?php

namespace app\service;


use app\exception\ModelException;
use app\model\Attachment;
use app\model\Category;
use app\model\Route;
use app\model\WebsiteLang;
use think\facade\Db;
use function GuzzleHttp\Psr7\str;

class CategoryService {

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws ModelException
     */
    public function readCategory($param): \think\response\Json
    {
        $category = new Category();
        $res = $category->getCategory($param);
        if(!empty($res['data']['thumbnail'])){
            $attachment = new Attachment();
            $whereThumb = ['id' => $res['data']['thumbnail']];
            $thumbnail = $attachment->getAttachment($whereThumb)['data'];
            $res['data']['thumbnail'] = $thumbnail;
        }
        return json($res);
    }

    /**
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function createCategory(&$param): \think\response\Json
    {
        $category = new Category();
        Db::startTrans();
        try {
            // 完善栏目数据
            if ($param['parent_id']) {
                $parentCate = $category->getCategory(['id' => $param['parent_id'], 'seller_id' => $param['seller_id']])['data'];
                $param['path'] = $parentCate['path'] . '-' . $param['parent_id'];
                if(empty($param['module_id'])){
                    $param['module_id'] = $parentCate['module_id'];
                }
            } else {
                $param['path'] = 0;
            }
            $maxOrder = $category->getMaxOrderCategory(['parent_id' => $param['parent_id']], 'sort')['data'];
            if (!empty($maxOrder)) {
                $param['sort'] = (int)$maxOrder + 10;
            }
            if(isset($param['alias'])){
                $param['alias'] = $this->dealWithAlias($param['alias']);
            }
            $cate = $category->addCategory($param);
            // 美化url
            if (!empty($param['alias']) && in_array($param['type'],[1,4]) ){
                $routeParam = [
                    'alias' => $param['alias'],
                    'type' => $param['type'],
                    'lang' => $param['lang'],
                    'sort' => 1000,
                    'website_id' => $param['website_id'],
                    'seller_id' => $param['seller_id'],
                    'title' => $cate['data']['title'],
                    'detail_sort' => 4999,
                    'id' => $cate['data']['id']
                ];

                $this->setRoute($routeParam);
            }
            // 操作日志
            optEventLog($cate['data']['id'],'栏目','添加');
            Db::commit();
        }catch (ModelException $me){
            Db::rollback();
            return jsonReturn(-5,$me->getMessage());
        }catch (\Exception $e){
            Db::rollback();
            return jsonReturn(-6,$e->getMessage());
        }
        return json($cate);
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws ModelException
     */
    public function updateCategory($param): \think\response\Json
    {
        $category = new Category();
        $cate = $category->getCategory(['id'=>$param['id'],'seller_id'=>$param['seller_id']])['data'];
        Db::startTrans();
        try{
            if(isset($param['alias'])){
                $param['alias'] = $this->dealWithAlias($param['alias']);
            }
            if($cate['alias'] != $param['alias']){
                $routeParam = [
                    'alias' => $param['alias'],
                    'type' => $param['type'],
                    'sort' => 1000,
                    'lang' => $param['lang'],
                    'website_id' => $param['website_id'],
                    'seller_id' => $cate['seller_id'],
                    'title' => $param['title'],
                    'detail_sort' => 4999,
                    'id' => $param['id'],
                ];
                $this->setRoute($routeParam);
            }
            $res = $category->updateCategory(['id'=>$param['id'],'seller_id'=>$param['seller_id']],$param);
            optEventLog($param['id'],'栏目','更新');
            Db::commit();
        }catch (ModelException $me){
            Db::rollback();
            return jsonReturn(-7,$me->getMessage());
        }catch (\Exception $e){
            Db::rollback();
            return jsonReturn(-8,$e->getMessage());
        }
        return json($res);
    }

    /**
     * @throws ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function setRoute($param)
    {
        $route = new Route();
        $route->setRoute($param['alias'], 'List/index', ['id' => $param['id']], $param['lang'],$param['type'], $param['sort'], $param['seller_id'],$param['id'],$param['website_id'],$param['title']);
        if($param['type'] == 1){
            $pattern = json_encode(['id'=>'\d+','cid'=>'\d+']);
            $route -> setRoute($param['alias'].'/:id','Detail/index',['cid' => $param['id']], $param['lang'], $param['type'], $param['sort'], $param['seller_id'],$param['id'],$param['website_id'],$param['title'].'详情页',$pattern);
        }
        $route->getRoutes($param['website_id'], $param['seller_id'], $param['lang']);
    }

    public function dealWithAlias($alias): string
    {
        $alias = trim($alias);
        if(strlen($alias) >= 1){
            $tmpAlias = rtrim($alias, '/');
            if(strlen($tmpAlias)){
                $alias = $tmpAlias;
            }else{
                $alias = '/';
            }
        }else{
            $alias = '';
        }
        return $alias;
    }

}
